using System.IO;
using System.Linq;
using System.Security.AccessControl;
using System.Security.Principal;

namespace AccessBasedDesktop.Core
{
    /// <summary>
    /// Common classes extentinos
    /// </summary>
    public static class ClassExtensions
    {
        /// <summary>
        /// Convert FileSystemInfo ACL to string
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static string GetAccessString(this FileSystemInfo source)
        {
            string result = null;
            var fileInfo = source as FileInfo;
            if (fileInfo != null && fileInfo.Exists)
            {
                result = string.Join(",", 
                        fileInfo.GetAccessControl(AccessControlSections.All)
                        .GetAccessRules(true, false, typeof(NTAccount))
                        .Cast<FileSystemAccessRule>()
                        .Select(x => x.GetStateString())
                    );
            }
            return result;
        }

        /// <summary>
        /// Convert FileSystemAccessRule to string
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static string GetStateString(this FileSystemAccessRule source)
        {
            return source.FileSystemRights + " " + source.IdentityReference.Value + " " +
                   source.AccessControlType;
        }
    }
}